import { useEffect, useState } from 'react';
import { Card, Image,  Pagination, Row, Col, Spin } from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom'; // 导入 Link
import './index.css';
import speechsvg from '../../../assets/speech/like.svg';
import downsvg from '../../../assets/down.svg'

const { Meta } = Card;

const SpeechFirstPage = () => {
  const [books, setBooks] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true); 
  const booksPerPage = 8;

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        const response = await axios.get('/api/books');
        console.log('Fetched books:', response.data); 

        // 提取 data 数组
        const actualBooks = response.data.data || [];
        setBooks(actualBooks);
      } catch (error) {
        console.error('Error fetching books:', error);
      } finally {
        setLoading(false); 
      }
    };

    fetchBooks();
  }, []);

  const indexOfLastBook = currentPage * booksPerPage;
  const indexOfFirstBook = indexOfLastBook - booksPerPage;
  const currentBooks = books.slice(indexOfFirstBook, indexOfLastBook);

  const paginate = pageNumber => setCurrentPage(pageNumber);

  return (
    <div className='speechF-book-list-container'>
      <div style={{ marginTop: '30px', marginBottom: '40px' }}>
        <div className="speechF-header">
          <div className="speechF-speech-container">
            <img src={speechsvg} alt="SVG Image" className="speechF-svg-image" />
            <h1>Unlock Your Potential With Oral English Ability</h1>
            <p className='speechF-myh5'>Conquer English speaking with ease on LinguaLeap!
              Our platform is your go-to for interactive practice, instant feedback, and a community that empowers you to speak fluently.<br></br>
              Say farewell to language limits and hello to confident communication. Start your journey to English mastery today!</p>
          </div>
        </div>
      </div>
  
      <div>
        <div className="speechF-speech-container">
          <p className='speechF-p1'>Choose What You Want To Exercise</p>
          <img src={downsvg} alt="SVG Image" className="speechF-down-svg-image" />
        </div>
      </div>
  
      {loading ? (
        <Spin size="large" style={{ margin: '0 auto', display: 'block' }} />
      ) : (
        <>
          <Row gutter={[48, 48]} className="speechF-row-of-cards">
            {Array.isArray(currentBooks) && currentBooks.map(book => (
              <Col key={book.bookId || book.title} xs={24} sm={12} md={8} lg={6} xl={6} className="speechF-card-item">
                <Link to={`/dialogue/${book.bookId || book.title}/chapter`} key={book.bookId || book.title}>
                  <Card
                    cover={
                      <Image
                        src={`data:image/jpeg;base64,${book.picture}`}
                        alt={book.title}
                        preview={false}
                      />
                    }
                    bordered={true}
                    className="speechF-small-card-content speechF-card-hover-effect" 
                  >
                      {/* 使用 div 包裹 title 并添加自定义类名 */}
                      <div className="speechF-card-title">
                         {book.title}
                      </div>
                    <Meta 
                      description={<div className='speechF-description'>{book.description}</div>} 
                      />
                  </Card>
                </Link>
              </Col>
            ))}
          </Row>
          <Pagination
            current={currentPage}
            total={books.length}
            pageSize={booksPerPage}
            onChange={paginate}
            showSizeChanger={false}
            style={{ textAlign: 'center', marginTop: '20px', marginBottom: '50px' }}
          />
        </>
      )}
    </div>
  );
};

export default SpeechFirstPage;